package cn.pegasus.teamwork.appinterface.controller.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;

import cn.iyizhan.teamwork.base.util.ObjectUtil;
import cn.iyizhan.teamwork.base.util.ReadPro;
import cn.pegasus.teamwork.appinterface.base.BaseController;
import cn.pegasus.teamwork.appinterface.util.ParameterEunm;
import cn.pegasus.teamwork.appinterface.util.ReturnRsUtils;
import cn.pegasus.teamwork.pegasus.entity.BussCarsConfig;
import cn.pegasus.teamwork.pegasus.entity.BussNewsInfo;
import cn.pegasus.teamwork.pegasus.entity.BussRechargeConfig;
import cn.pegasus.teamwork.pegasus.service.BussCarsConfigService;
import cn.pegasus.teamwork.pegasus.service.BussNewsInfoService;
import cn.pegasus.teamwork.pegasus.service.BussRechargeConfigService;
import cn.pegasus.teamwork.sysconfig.entity.SysConfigDictionary;
import cn.pegasus.teamwork.sysconfig.service.SysConfigDictionaryService;
import cn.pegasus.teamwork.sysconfig.service.SysConfigSmsService;
import cn.pegasus.teamwork.util.OSSClientUtil;

/**
 * @ClassName: SysUcenerUserController
 * @Description: 用户控制中心
 * @author ryan.bian
 * @date 2017年11月12日 上午10:10:32
 * 
 *       包括以下主要几个接口： ================================= 1.发送短信验证码 2.文件上传-oss
 *       3.微信支付 ================================
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/pub/*")
public class UserPubController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserPubController.class);

	@Autowired
	private SysConfigSmsService configSmsService;
	
	@Autowired
	private BussRechargeConfigService rechargeConfigService;
	
	@Autowired
	private BussNewsInfoService newsInfoService;
	
	
	@Autowired
	private SysConfigDictionaryService dictionaryService;
	
	@Autowired
	private BussCarsConfigService carsConfigService;

	/**
	 * 发送短信验证码
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/sm", method = RequestMethod.POST)
	public Map<String, Object> sendMsg(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "phone", "type" }, map);
		// userId 是可选项
		// 1:异常 0:成功 ;2-时间不到，请勿重新发送
		if (isNotNull) {
			try {
				long userId = 0;
				if (map.get("userId") != null) {
					userId = Long.valueOf(map.get("userId").toString());
				}
				long phone = Long.valueOf(map.get("phone").toString());
				int type = Integer.valueOf(map.get("type").toString());
				int rs = configSmsService.createCode(phone, userId, type);
				if (rs == 0) {
					resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE,true);
				} else if (rs == 1) {
					resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE,false);
				} else if (rs == 2) {
					resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE,false);
				}
			} catch (Exception e) {
				LOGGER.error("服务器异常!", e);
				resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE,false);
			}
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE, null);
		}
		LOGGER.info("返回参数 ：{}", JSONObject.toJSON(resultMap));
		return resultMap;
	}

	/**
	 * 发送短信验证码
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/csm", method = RequestMethod.POST)
	public Map<String, Object> checkSms(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "phone", "type", "code" }, map);
		if (isNotNull) {
			try {
				long userId = 0;
				if (map.get("userId") != null) {
					userId = Long.valueOf(map.get("userId").toString());
				}
				long phone = Long.valueOf(map.get("phone").toString());
				int type = Integer.valueOf(map.get("type").toString());
				String code = map.get("code").toString();
				boolean rs = configSmsService.checkSms(phone, userId, type, code);
				if (rs) {
					resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE,true);
				} else {
					resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE,false);
				}
			} catch (Exception e) {
				LOGGER.error("服务器异常!", e);
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE, null);
			}
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE, null);
		}
		LOGGER.info("返回参数 ：{}", JSONObject.toJSON(resultMap));
		return resultMap;
	}

	/**
	 * 用户充值选择列表
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/rcl", method = RequestMethod.POST)
	public Map<String, Object> rechargeConfigList(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "configType" }, map);
		if (isNotNull) {
			map.put("configType", map.get("configType"));
			List<BussRechargeConfig> newuses = rechargeConfigService.findLists(map);
			if (newuses != null && newuses.size() > 0) {
				Map<String, Object> maps = new HashMap<String, Object>();
				maps.put("lis", newuses);
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, maps);
			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
			}
		}		
		
		return resultMap;
	}
	
	/**
	 * 关于我们和帮助中心
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/abt", method = RequestMethod.POST)
	public Map<String, Object> about(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "type" }, map);
		if (isNotNull) {
			map.put("newsType", map.get("type"));
			BussNewsInfo newuses = newsInfoService.detail(map);
				Map<String, Object> maps = new HashMap<String, Object>();
				maps.put("rs", newuses);
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, maps);			
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		}	
		
		return resultMap;
	}
	
	
	/**
	 * 车辆颜色
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/ccl", method = RequestMethod.POST)
	public Map<String, Object> carcolor(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		map.put("dictValue", "carChooseColor");

		SysConfigDictionary c = dictionaryService.detail(map);
		int id = c.getId();
		Map<String, Object> tMap = new HashMap<String, Object>();
		tMap.put("dictPvalue", id);
		List<SysConfigDictionary> lis = dictionaryService.query(tMap);
		if(lis != null && lis.size() > 0){
			List<String> names = new ArrayList<String>();
			for(SysConfigDictionary li : lis){
				names.add(li.getDictValue());
			}
			Map<String, Object> maps = new HashMap<String, Object>();
			maps.put("rs", names);
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, maps);		
			
		}else{
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		} 
		return resultMap;
	}

	/**
	 * 查询车辆品牌列表
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cbd", method = RequestMethod.POST)
	public Map<String, Object> carBrand(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		map.put("fid", "-1");

		List<BussCarsConfig> lis = carsConfigService.query(map);

		if(lis != null && lis.size() > 0){
			Map<String, Object> maps = new HashMap<String, Object>();
			maps.put("rs", lis);
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, maps);		
			
		}else{
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		} 
		return resultMap;
	}
	
	
	/**
	 * 根据车辆品牌查查车辆信息
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/qcb", method = RequestMethod.POST)
	public Map<String, Object> queryCarByBrand(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "id" }, map);
		if (isNotNull) {
			Map<String, Object> tMap = new HashMap<String, Object>();
			tMap.put("fid", map.get("id"));
			List<BussCarsConfig> lis = carsConfigService.query(tMap);
			if(lis != null && lis.size() > 0){
				Map<String, Object> maps = new HashMap<String, Object>();
				maps.put("rs", lis);
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, maps);				
			}else{
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
			}			
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		}
		return resultMap;
	}
	
	
	/**
	 * 文件上传，输出文件存储路径
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = { "/upf" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadFile(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> tMap = new HashMap<String, Object>();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			LOGGER.info("开始执行文件上传方法。获取到的参数为 ：" + request);
			if (multipartResolver.isMultipart(request)) {
				LOGGER.info("获取到参数");
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				// 此处只上传单个文件，如果需要多个文件只需要改为while循环上传
				if (iter.hasNext()) {
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					LOGGER.info("" + pre);
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {

						OSSClientUtil util = new OSSClientUtil();
						String rs = util.uploadImg2Oss(file);
						if (!StringUtils.isEmpty(rs)) {
							tMap.put("filePath", rs);
							resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE,tMap);
						} else {
							resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE,null);
						}
					}
				} else {
					resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE,null);
				}
			} else {
				resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE,null);
			}
		} catch (Exception e) {
			LOGGER.error("服务器异常!", e);
			resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE,null);
		}

		LOGGER.info("返回参数 ：{}", JSONObject.toJSON(resultMap));
		return resultMap;
	}
	
	
	
	/**
	 * 根据车辆品牌查查车辆信息
	 * 
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/qbis", method = RequestMethod.POST)
	public Map<String, Object> queryBankInfos(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> resultMaps = new HashMap<String, Object>();
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		String config_bankNames = ReadPro.getValue("config_bankNames").toString();
		if (!StringUtils.isEmpty(config_bankNames)) {
			String[] bankNames = 	config_bankNames.split(";");
			if(bankNames != null && bankNames.length > 0){
				for (int i = 0; i < bankNames.length; i++) {
					String[] names = bankNames[i].split(":");
					if(names != null){
						Map<String, Object> result = new HashMap<String, Object>();
						result.put("name", names[0]);
						result.put("length", names[1]);
						maps.add(result);
					}
				}
				resultMaps.put("rs", maps);
				resultMap =  ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE,resultMaps);
			}
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		}
		return resultMap;
	}
	
}
